//
//  FaceDetectManageer.m
//  CamH
//
//  Created by xqiu on 12-8-12.
//  Copyright (c) 2012年 ghu. All rights reserved.
//

#import "FaceDetectManager.h"
#import "ImageHelper.h"

#define FACEDETECT_DEFAULT_BUFFERSIZE 1024*1024*10

@interface FaceDetectManager()
{
    WXFaceResult lastResult[10];
}
@end

@implementation FaceDetectManager
@synthesize m_pHandle;
@synthesize m_pParam;

-(id) initWithWidth:(NSUInteger)width height:(NSUInteger)height
{
    [super init];
    // 初始化m_pHandle
    self.m_pHandle = malloc(sizeof(WXFDHandle));
    if (!self.m_pHandle) 
        return nil;
    self.m_pHandle->pBuffer = malloc(FACEDETECT_DEFAULT_BUFFERSIZE);
    if (!self.m_pHandle->pBuffer) 
        return nil;
    self.m_pHandle->BufferLen = FACEDETECT_DEFAULT_BUFFERSIZE;
    self.m_pHandle->useLen = 0;
    
    // 初始化m_pParam
    self.m_pParam = malloc(sizeof(WXFDParam));
    if (!self.m_pParam)
        return nil;
    self.m_pParam->width = width;
    self.m_pParam->height = height;
    self.m_pParam->scale = 1280;
    self.m_pParam->step = 2;
    self.m_pParam->minwidth = 20;    
    self.m_pParam->SDSen = 1;
    
    if (FD_WXInit(self.m_pHandle, self.m_pParam, FD_W3))
        return self;
    else
        return nil ;
}

-(NSInteger)detectFaceFromBuffer:(CMSampleBufferRef)buffer result:(WXFaceResult*)result
{
    int nFace = 0;
   
    unsigned char *pGrayData = [ImageHelper bitmapGrayFromCMSampleBuffer:buffer];
    nFace = FD_WXProcess(m_pHandle, m_pParam, pGrayData, FD_W3, result);
    free(pGrayData);
    NSLog(@"人脸数:%d", nFace);

    return nFace;
}


-(NSInteger)detectFaceFromImage:(UIImage*)image result:(WXFaceResult*)result
{
    int nFace = 0;
    float fitInScale=0;
    CGPoint fitInOffset={0};
    UIImage *fitInImage = [ImageHelper image:image fitInSize:CGSizeMake(m_pParam->width,m_pParam->height) fitInScale:&fitInScale fitInOffsetPoint:&fitInOffset];
    unsigned char *pGrayData = [ImageHelper bitmapGrayFromImage:fitInImage];
    nFace = FD_WXProcess(m_pHandle, m_pParam, pGrayData, FD_W3, result );
    
    NSLog(@"fitInScale=%f, offsetPoint.x=%f, y=%f", fitInScale, fitInOffset.x, fitInOffset.y);
    NSLog(@"人脸数:%d", nFace);
    
    free(pGrayData);
    return nFace;
}

-(BOOL)processWithInputResult:(WXFaceResult*)input output:()output
{
    
}

@end













